package com.bhald.CJ.Common;

import java.io.File;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.ParseException;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.Gravity;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.bhald.CJ.lock.R;

public class CommonM {
	/*
	 * 
	 */
	@SuppressLint("SimpleDateFormat")
	public static String gettomorrowDate(int da) {
		String days = "";
		Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH);
		int day = c.get(Calendar.DAY_OF_MONTH);
		String mon = getmonth(month + 1);

		if (da == 0) {
			//
			days = year + "-" + mon + "-" + (day - 1);
		} else if (da == 1) {
			//
			days = year + "-" + mon + "-" + day;
		} else if (da == 2) {
			//
			days = year + "-" + mon + "-" + (day + 1);
		} else if (da == 3) {
			//
			days = year + "";
		} else if (da == 4) {
			int hour = c.get(Calendar.HOUR_OF_DAY);
			int minute = c.get(Calendar.MINUTE);
			int seconds = c.get(Calendar.SECOND);
			// yyyymmdd_hhffmm
			days = year + "" + (month + 1) + "" + day + "" + hour + minute
					+ seconds;
		} else if (da == 5) {
			days = year + "-" + mon + "-" + (day - 2);
		}
		return days;
	}

	// �遢
	public static String getmonth(int month) {
		String mon = "";
		String m = String.valueOf(month);
		if (m.length() == 1) {
			mon = "0" + m;
		} else {
			mon = m;
		}
		return mon;
	}

	// 岆瘁羲ぎ厙釐
	public static boolean IsHaveInternet(final Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		int i = 0;
		if (connectivity != null) {
			NetworkInfo[] infos = connectivity.getAllNetworkInfo();
			if (infos != null) {
				for (NetworkInfo info : infos) {
					if (info.getState() == NetworkInfo.State.CONNECTED) {
						i++;
					}
				}
			}
		}
		if (i > 0) {
			return true;
		} else {
			return false;
		}
	}

	// 瓚剿督昢岆瘁婓堍俴
	public static boolean isServiceRunning(Context mContext, String className) {

		boolean isRunning = false;
		ActivityManager activityManager = (ActivityManager) mContext
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo> serviceList = activityManager
				.getRunningServices(30);

		if (!(serviceList.size() > 0)) {
			return false;
		}

		for (int i = 0; i < serviceList.size(); i++) {
			if (serviceList.get(i).service.getClassName().equals(className) == true) {
				isRunning = true;
				break;
			}
		}
		return isRunning;
	}

	// call
	public static void autoCallTelephone(Context context, String phoneNumber) {
		Intent intent = new Intent(Intent.ACTION_CALL);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri telUri = Uri.parse("tel://" + phoneNumber);
		intent.setData(telUri);
		context.startActivity(intent);
	}

	// send SMS
	public static void autoSendSMS(Context context, String phoneNumber,
			String msg) {
		PendingIntent paIntent = PendingIntent.getBroadcast(context, 0,
				new Intent("SMS_SENT"), 0);

		SmsManager smsManager = SmsManager.getDefault();
		smsManager.sendTextMessage(phoneNumber, null, msg, paIntent, null);
	}

	public static void showAutoCallDialog(final Context context,
			final String phoneNumber) {
		new AlertDialog.Builder(context).setTitle("拨打电话")
				.setMessage("确定拨打:" + phoneNumber + " ?")
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// 赻雄畢瘍
						CommonM.autoCallTelephone(context, phoneNumber);
					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				}).show();
	}

	static Dialog mDialog;

	//
	public static MyDialog addDialog(Context mContext, LinearLayout linear) {
		MyDialog myDialog = new MyDialog(mContext);
		myDialog.startAnimation(linear);
		return myDialog;
	}

	//
	public static MyDialog addDialog(Context mContext, LinearLayout linear,
			String text) {
		MyDialog myDialog = new MyDialog(mContext);
		myDialog.startAnimation(linear, text);
		return myDialog;
	}

	//
	public static String[] getImageNames(String folderPath) {
		File file01 = new File(folderPath);
		String[] files01 = file01.list();
		if (files01 == null)
			return null;
		int imageFileNums = 0;
		for (int i = 0; i < files01.length; i++) {
			File file02 = new File(folderPath + "/" + files01[i]);
			if (!file02.isDirectory()) {
				if (isImageFile(file02.getName())) {
					imageFileNums++;
				}
			}
		}
		String[] files02 = new String[imageFileNums];

		int j = 0;
		for (int i = 0; i < files01.length; i++) {
			File file02 = new File(folderPath + "/" + files01[i]);

			if (!file02.isDirectory()) {

				if (isImageFile(file02.getName())) {
					files02[j] = file02.getName();
					j++;
				}
			}
		}

		return files02;
	}

	//
	private static boolean isImageFile(String fileName) {
		String fileEnd = fileName.substring(fileName.lastIndexOf(".") + 1,
				fileName.length());
		if (fileEnd.equalsIgnoreCase("jpg")) {
			return true;
		} else if (fileEnd.equalsIgnoreCase("png")) {
			return true;
		} else if (fileEnd.equalsIgnoreCase("bmp")) {
			return true;
		} else {
			return false;
		}
	}

	//
	public static Bitmap convertToBitmap(String path, int w, int h) {
		BitmapFactory.Options opts = new BitmapFactory.Options();
		//
		opts.inJustDecodeBounds = true;
		opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
		//
		BitmapFactory.decodeFile(path, opts);
		int width = opts.outWidth;
		int height = opts.outHeight;
		float scaleWidth = 0.f, scaleHeight = 0.f;
		if (width > w || height > h) {
			//
			scaleWidth = ((float) width) / w;
			scaleHeight = ((float) height) / h;
		}
		opts.inJustDecodeBounds = false;
		float scale = Math.max(scaleWidth, scaleHeight);
		opts.inSampleSize = (int) scale;
		WeakReference<Bitmap> weak = new WeakReference<Bitmap>(
				BitmapFactory.decodeFile(path, opts));
		return Bitmap.createScaledBitmap(weak.get(), w, h, true);
	}

	//
	public static List<String> getList(String s) {
		List<String> str = new ArrayList<String>();
		String[] string = s.split(",");
		int count = string.length;
		for (int i = 0; i < count; i++) {
			str.add(string[i]);
		}
		return str;
	}

	//
	public static List<String> getMusicData(String sss) {
		List<String> data = new ArrayList<String>();
		if (sss.equals("")) {
			return data;
		}
		List<String> list = getList(sss);
		for (int i = 0; i < list.size(); i++) {
			String path = list.get(i).toString();
			Log.e("CommonM.getMusicData", path);
			data.add(path);
		}
		return data;
	}

	public static void closeKey(IBinder windowToken, Context context) {
		InputMethodManager imm = (InputMethodManager) context
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(windowToken, 0);
	}

	// Distinguish the Numbers
	public static boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}

	@SuppressLint("ResourceAsColor")
	public static void ShowSmallDialog(Context context, String Str, int id) {

		Toast toast = Toast.makeText(context, Str, Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.CENTER, 0, 0);

		LinearLayout toastView = (LinearLayout) toast.getView();
		toastView.setBackgroundColor(Color.GRAY);
		// ㇄⑵
		ImageView imageCodeProject = new ImageView(context);
		imageCodeProject.setImageResource(id);

		toastView.setBackgroundColor(R.color.blacks);
		// toastView.addView(text);
		toastView.addView(imageCodeProject, 0);
		toast.show();
	}

	//
	public static void clearUser(SharedPreferences sp) {
		Editor editor = sp.edit();
		editor.putString("uname", null);
		editor.putString("upswd", null);
		editor.putBoolean("auto", false);
		editor.commit();
	}

	// check sd exist
	public static boolean CheckSD() {
		boolean sd = false;
		String status = Environment.getExternalStorageState();
		if (status.equals(Environment.MEDIA_MOUNTED)) {
			sd = true;
		} else {
			sd = false;
		}
		return sd;
	}

	// Create Lock File
	public static void CreateLockFile(String sDir) {
		File destDir = new File(sDir);
		if (!destDir.exists()) {
			destDir.mkdirs();
		}
	}

	// File exists
	public static boolean existsFile(String sDir) {
		boolean state = false;
		File destDir = new File(sDir);
		if (destDir.exists()) {
			state = true;
		}
		return state;
	}

	public static Date ParseDate(String str){
		SimpleDateFormat dateFormat =new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); 
		Date addTime = null;
		try {
			addTime = dateFormat.parse(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return addTime;
	}
}
